// ========== 全局状态管理 ==========
const AppState = {
    currentReagentConfig: null,     // 当前应用的试剂配置
    currentInjectConfig: null,      // 当前应用的反应流程
    deviceStatus: 'idle',           // 设备状态
    temperature: 25.0,              // 当前温度
    isReagentLocked: false,         // 试剂配置是否锁定
    availableReagents: [],          // 可用试剂列表
    stepCounter: 0,                 // 步骤计数器
    lastUpdateTime: null,           // 最后更新时间
    currentStepIndex: 0,            // 当前步骤索引
    currentCycleCount: 0,           // 当前循环计数
    currentStepInfo: '',            // 当前步骤信息
    nextActionInfo: '',             // 下一个动作信息
    reactionPaused: false,          // 反应是否暂停
    sseConnected: false,            // SSE连接状态
    reconnectAttempts: 0            // 重连尝试次数
};

// ========== 页面初始化 ==========
document.addEventListener('DOMContentLoaded', function() {
    console.log('页面加载完成，开始初始化...');
    
    // 初始化所有事件监听器
    initializeEventListeners();
    
    // 加载系统状态
    loadSystemStatus();
    
    // 设置增强的状态流监听
    setupEnhancedStatusStream();
    
    // 加载配置列表
    loadAllConfigs();
    
    // 设置定期轮询作为备用方案
    setupPollingFallback();
    
    console.log('初始化完成');
});

// ========== 增强的SSE连接管理 ==========
let statusEventSource = null;
let reconnectTimer = null;
let pollingTimer = null;

function setupEnhancedStatusStream() {
    // 如果已存在连接，先关闭
    if (statusEventSource) {
        statusEventSource.close();
    }
    
    console.log('建立SSE连接...');
    statusEventSource = new EventSource('/status_stream');
    
    // 连接打开事件
    statusEventSource.onopen = function() {
        console.log('SSE连接已建立');
        AppState.sseConnected = true;
        AppState.reconnectAttempts = 0;
        
        // 清除重连定时器
        if (reconnectTimer) {
            clearTimeout(reconnectTimer);
            reconnectTimer = null;
        }
        
        // 显示连接状态
        updateConnectionStatus(true);
    };
    
    // 接收消息事件
    statusEventSource.onmessage = function(event) {
        try {
            // 忽略心跳包注释
            if (event.data.startsWith(':')) {
                return;
            }
            
            const data = JSON.parse(event.data);
            
            // 检测状态变化
            const stateChanged = detectStateChanges(data);
            
            // 更新应用状态
            updateAppStateFromSSE(data);
            
            // 如果有变化，更新UI
            if (stateChanged) {
                console.log('检测到状态变化，更新UI');
                debouncedStatusUpdate();
            }
            
            // 更新最后更新时间
            AppState.lastUpdateTime = new Date();
            
        } catch (error) {
            console.error('解析SSE数据失败:', error);
        }
    };
    
    // 错误事件
    statusEventSource.onerror = function(error) {
        console.error('SSE连接错误:', error);
        AppState.sseConnected = false;
        
        // 更新连接状态显示
        updateConnectionStatus(false);
        
        // 关闭当前连接
        if (statusEventSource) {
            statusEventSource.close();
            statusEventSource = null;
        }
        
        // 清除之前的重连定时器
        if (reconnectTimer) {
            clearTimeout(reconnectTimer);
            reconnectTimer = null;
        }
        
        // 实施指数退避重连策略
        AppState.reconnectAttempts++;
        const delay = Math.min(1000 * Math.pow(2, AppState.reconnectAttempts), 30000); // 最大30秒
        
        console.log(`将在 ${delay/1000} 秒后尝试重连... (第 ${AppState.reconnectAttempts} 次尝试)`);
        
        reconnectTimer = setTimeout(() => {
            setupEnhancedStatusStream();
        }, delay);
    };
}

// 检测状态变化
function detectStateChanges(newData) {
    const changes = [];
    
    // 检查各个字段的变化
    if (newData.device_status !== AppState.deviceStatus) {
        changes.push(`设备状态: ${AppState.deviceStatus} -> ${newData.device_status}`);
    }
    if (newData.temperature !== AppState.temperature) {
        changes.push(`温度: ${AppState.temperature} -> ${newData.temperature}`);
    }
    if (newData.reagent_locked !== AppState.isReagentLocked) {
        changes.push(`试剂锁定: ${AppState.isReagentLocked} -> ${newData.reagent_locked}`);
    }
    if (newData.reaction_paused !== AppState.reactionPaused) {
        changes.push(`反应暂停: ${AppState.reactionPaused} -> ${newData.reaction_paused}`);
    }
    if (newData.current_reagent_config !== AppState.currentReagentConfig) {
        changes.push(`试剂配置: ${AppState.currentReagentConfig} -> ${newData.current_reagent_config}`);
    }
    if (newData.current_inject_config !== AppState.currentInjectConfig) {
        changes.push(`反应流程: ${AppState.currentInjectConfig} -> ${newData.current_inject_config}`);
    }
    if (newData.current_step_index !== AppState.currentStepIndex) {
        changes.push(`当前步骤: ${AppState.currentStepIndex} -> ${newData.current_step_index}`);
    }
    if (newData.current_cycle_count !== AppState.currentCycleCount) {
        changes.push(`循环计数: ${AppState.currentCycleCount} -> ${newData.current_cycle_count}`);
    }
    
    if (changes.length > 0) {
        console.log('状态变化:', changes);
    }
    
    return changes.length > 0;
}

// 从SSE数据更新应用状态
function updateAppStateFromSSE(data) {
    AppState.deviceStatus = data.device_status || 'idle';
    AppState.temperature = data.temperature || 25.0;
    AppState.isReagentLocked = data.reagent_locked || false;
    AppState.reactionPaused = data.reaction_paused || false;
    AppState.currentStepIndex = data.current_step_index || 0;
    AppState.currentCycleCount = data.current_cycle_count || 0;
    AppState.currentStepInfo = data.current_step_info || '';
    AppState.nextActionInfo = data.next_action_info || '';
    AppState.currentReagentConfig = data.current_reagent_config || null;
    AppState.currentInjectConfig = data.current_inject_config || null;
    AppState.tecConnected = data.tec_connected || false;
    AppState.pumpConnected = data.pump_connected || false;
}

// 设置轮询备用方案
function setupPollingFallback() {
    // 每10秒检查一次连接状态
    setInterval(() => {
        if (!AppState.sseConnected) {
            console.log('SSE断开，使用轮询获取状态');
            fetchSystemStatus();
        }
    }, 10000);
}

// 轮询获取系统状态
async function fetchSystemStatus() {
    try {
        const response = await fetch('/api/system/status');
        const data = await response.json();
        
        if (data.success) {
            const stateChanged = detectStateChanges(data);
            updateAppStateFromSSE(data);
            
            if (stateChanged) {
                debouncedStatusUpdate();
            }
        }
    } catch (error) {
        console.error('轮询状态失败:', error);
    }
}

// 更新连接状态显示
function updateConnectionStatus(connected) {
    // 可以在页面上添加一个小的连接状态指示器
    const existingIndicator = document.getElementById('connection-indicator');
    if (existingIndicator) {
        existingIndicator.remove();
    }
    
    const indicator = document.createElement('div');
    indicator.id = 'connection-indicator';
    indicator.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        padding: 8px 15px;
        border-radius: 20px;
        font-size: 12px;
        color: white;
        background: ${connected ? '#27ae60' : '#e74c3c'};
        box-shadow: 0 2px 8px rgba(0,0,0,0.2);
        z-index: 9999;
        transition: all 0.3s ease;
    `;
    indicator.innerHTML = `
        <i class="fas fa-${connected ? 'wifi' : 'exclamation-triangle'}"></i>
        ${connected ? '实时连接' : '连接断开'}
    `;
    
    document.body.appendChild(indicator);
    
    // 连接恢复后3秒自动隐藏
    if (connected) {
        setTimeout(() => {
            if (indicator && indicator.parentNode) {
                indicator.style.opacity = '0';
                setTimeout(() => indicator.remove(), 300);
            }
        }, 3000);
    }
}

// ========== 事件监听器初始化 ==========
function initializeEventListeners() {
    // 复选框change事件监听
    const checkboxes = [
        'reset_check', 'fill_check', 'wash_check', 
        'empty_check', 'reaction_check'
    ];
    
    checkboxes.forEach(id => {
        const checkbox = document.getElementById(id);
        if (checkbox) {
            checkbox.addEventListener('change', function() {
                updateButtonState(this);
            });
        }
    });
    
    // 主要操作按钮事件监听
    const operationButtons = [
        { id: 'reset_btn', action: 'reset' },
        { id: 'fill_btn', action: 'fill_tube' },
        { id: 'wash_btn', action: 'wash' },
        { id: 'empty_btn', action: 'empty' },
        { id: 'reaction_btn', action: 'reaction' },
        { id: 'reset-card-btn', action: 'reset' },
        { id: 'stop-card-btn', action: 'stop' },
        { id: 'pause-btn', action: 'pause' },
        { id: 'resume-btn', action: 'resume' }
    ];
    
    operationButtons.forEach(({ id, action }) => {
        const button = document.getElementById(id);
        if (button) {
            button.addEventListener('click', function(event) {
                event.preventDefault();
                sendOperation(action);
            });
        }
    });
    
    // 模态框相关按钮
    const modalButtons = [
        { id: 'reagent-config-btn', modal: 'reagent-modal' },
        { id: 'inject-config-btn', modal: 'inject-modal' }
    ];
    
    modalButtons.forEach(({ id, modal }) => {
        const button = document.getElementById(id);
        if (button) {
            button.addEventListener('click', function() {
                openModal(modal);
            });
        }
    });
    
    // 关闭模态框按钮
    document.querySelectorAll('.close-modal').forEach(button => {
        button.addEventListener('click', function() {
            const modal = this.closest('.modal');
            if (modal) {
                closeModal(modal.id);
            }
        });
    });
    
    // 点击模态框外部关闭
    document.querySelectorAll('.modal').forEach(modal => {
        modal.addEventListener('click', function(event) {
            if (event.target === this) {
                closeModal(this.id);
            }
        });
    });
    
    // 试剂配置相关按钮
    bindReagentConfigEvents();
    
    // 反应流程相关按钮
    bindInjectConfigEvents();
}

function bindReagentConfigEvents() {
    // 加载配置按钮
    const loadConfigBtn = document.getElementById('load_config_btn');
    if (loadConfigBtn) {
        loadConfigBtn.addEventListener('click', function() {
            const configSelect = document.getElementById('config_select');
            if (configSelect && configSelect.value) {
                loadReagentConfig(configSelect.value);
            } else {
                showNotification('请先选择要加载的配置', 'error');
            }
        });
    }
    
    // 删除配置按钮
    const deleteConfigBtn = document.getElementById('delete_config_btn');
    if (deleteConfigBtn) {
        deleteConfigBtn.addEventListener('click', deleteReagentConfig);
    }
    
    // 保存配置按钮
    const saveConfigBtn = document.getElementById('save_new_config_btn');
    if (saveConfigBtn) {
        saveConfigBtn.addEventListener('click', saveReagentConfig);
    }
    
    // 应用配置按钮
    const applyConfigBtn = document.getElementById('apply_reagent_config');
    if (applyConfigBtn) {
        applyConfigBtn.addEventListener('click', applyReagentConfig);
    }
    
    // 试剂输入框变化事件
    for (let i = 3; i <= 9; i++) {
        const input = document.querySelector(`input[name="reagent${i}"]`);
        if (input) {
            input.addEventListener('input', function() {
                updateAvailableReagents();
            });
        }
    }
}

function bindInjectConfigEvents() {
    // 加载流程按钮
    const loadInjectBtn = document.getElementById('load-inject-config-btn');
    if (loadInjectBtn) {
        loadInjectBtn.addEventListener('click', function() {
            const configSelect = document.getElementById('inject-config-select');
            if (configSelect && configSelect.value) {
                loadInjectConfig(configSelect.value);
            } else {
                showNotification('请先选择要加载的流程', 'error');
            }
        });
    }
    
    // 删除流程按钮
    const deleteInjectBtn = document.getElementById('delete-inject-config-btn');
    if (deleteInjectBtn) {
        deleteInjectBtn.addEventListener('click', deleteInjectConfig);
    }
    
    // 保存流程按钮
    const saveInjectBtn = document.getElementById('save-inject-config-btn');
    if (saveInjectBtn) {
        saveInjectBtn.addEventListener('click', saveInjectConfig);
    }
    
    // 应用流程按钮
    const applyInjectBtn = document.getElementById('apply-inject-config');
    if (applyInjectBtn) {
        applyInjectBtn.addEventListener('click', applyInjectConfig);
    }
    
    // 步骤管理按钮
    const addStepBtn = document.getElementById('add-step-btn');
    if (addStepBtn) {
        addStepBtn.addEventListener('click', addStep);
    }
    
    const clearStepsBtn = document.getElementById('clear-steps-btn');
    if (clearStepsBtn) {
        clearStepsBtn.addEventListener('click', function() {
            clearAllSteps(true);
        });
    }
}

// ========== 按钮状态管理 ==========
function updateButtonState(checkbox) {
    const checkboxId = checkbox.id;
    const buttonId = checkboxId.replace('_check', '_btn');
    const button = document.getElementById(buttonId);
    
    if (button) {
        button.disabled = !checkbox.checked;
        console.log(`按钮 ${buttonId} 状态更新: ${checkbox.checked ? '启用' : '禁用'}`);
    }
}

// ========== 模态框管理 ==========
function openModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.style.display = 'flex';
        document.body.style.overflow = 'hidden';
        
        // 如果是试剂配置模态框，更新关联的试剂配置显示
        if (modalId === 'inject-modal') {
            const linkedConfigElement = document.getElementById('linked-reagent-config');
            if (linkedConfigElement) {
                linkedConfigElement.textContent = AppState.currentReagentConfig || '未选择';
            }
        }
    }
}

function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.style.display = 'none';
        document.body.style.overflow = 'auto';
    }
}

// ========== 通知系统 ==========
function showNotification(message, type = 'success') {
    const notification = document.getElementById('notification');
    const notificationText = document.getElementById('notification-text');
    
    if (notification && notificationText) {
        notificationText.textContent = message;
        notification.className = 'message ' + (type === 'error' ? 'error' : '');
        notification.style.display = 'flex';
        
        // 添加时间戳
        const timestamp = new Date().toLocaleTimeString();
        console.log(`[${timestamp}] ${type.toUpperCase()}: ${message}`);
        
        // 3秒后自动隐藏
        setTimeout(() => {
            notification.style.display = 'none';
        }, 3000);
    }
}

// ========== 系统状态管理 ==========
async function loadSystemStatus() {
    try {
        const response = await fetch('/api/system/status');
        const data = await response.json();
        
        if (data.success) {
            // 更新全局状态
            updateAppStateFromSSE(data);
            
            // 更新UI显示
            debouncedStatusUpdate();
            
            // 如果有当前配置，加载到表单
            // if (AppState.currentReagentConfig) {
            //     loadReagentConfigToForm(AppState.currentReagentConfig);
            // }
            
            console.log("系统状态加载成功", AppState);
        }
    } catch (error) {
        console.error("加载系统状态失败:", error);
        showNotification("无法连接到设备，请检查连接", "error");
    }
}

// 防抖动函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 创建防抖动的状态更新函数
const debouncedStatusUpdate = debounce(updateStatusDisplay, 100);

function updateStatusDisplay() {
    // 更新设备状态
    const deviceStatusText = document.getElementById('device-status-text');
    const deviceStatusIndicator = document.getElementById('device-status-indicator');
    if (deviceStatusText && deviceStatusIndicator) {
        deviceStatusText.textContent = getStatusText(AppState.deviceStatus);
        deviceStatusIndicator.className = 'status-indicator ' + getStatusClass(AppState.deviceStatus);
    }
    
    // 更新温度
    const tempText = document.getElementById('temp-status-text');
    if (tempText) {
    if (AppState.tecConnected) {
        tempText.textContent = `${AppState.temperature.toFixed(1)}°C`;
    } else {
        tempText.textContent = `-- °C`;
    }
    }

    // 更新试剂配置状态
    const reagentStatusText = document.getElementById('reagent-status-text');
    const reagentStatusIndicator = document.getElementById('reagent-status-indicator');
    if (reagentStatusText && reagentStatusIndicator) {
        if (AppState.currentReagentConfig) {
            reagentStatusText.textContent = AppState.isReagentLocked ? '已锁定' : '已配置';
            reagentStatusIndicator.className = 'status-indicator ' + (AppState.isReagentLocked ? 'warning' : 'success');
        } else {
            reagentStatusText.textContent = '未配置';
            reagentStatusIndicator.className = 'status-indicator danger';
        }
    }
    
    // 更新反应流程状态
    const flowStatusText = document.getElementById('flow-status-text');
    const flowStatusIndicator = document.getElementById('flow-status-indicator');
    if (flowStatusText && flowStatusIndicator) {
        if (AppState.currentInjectConfig) {
            flowStatusText.textContent = '已选择';
            flowStatusIndicator.className = 'status-indicator success';
        } else {
            flowStatusText.textContent = '未选择';
            flowStatusIndicator.className = 'status-indicator';
        }
    }
    
    // 更新当前配置显示
    const currentReagentConfig = document.getElementById('current-reagent-config');
    const currentInjectConfig = document.getElementById('current-inject-config');
    if (currentReagentConfig) {
        currentReagentConfig.textContent = AppState.currentReagentConfig || '未选择';
    }
    if (currentInjectConfig) {
        currentInjectConfig.textContent = AppState.currentInjectConfig || '未选择';
    }
    

    const tecStatusText = document.getElementById('tec-status-text');
    const tecStatusIndicator = document.getElementById('tec-status-indicator');
    if (tecStatusText && tecStatusIndicator) {
    tecStatusText.textContent = AppState.tecConnected ? '已连接' : '未连接';
    tecStatusIndicator.className = 'status-indicator ' + (AppState.tecConnected ? 'success' : 'danger');
    }
    const pumpStatusText = document.getElementById('pump-status-text');
    const pumpStatusIndicator = document.getElementById('pump-status-indicator');
    if (pumpStatusText && pumpStatusIndicator) {
    pumpStatusText.textContent = AppState.pumpConnected ? '已连接' : '未连接';
    pumpStatusIndicator.className = 'status-indicator ' + (AppState.pumpConnected ? 'success' : 'danger');
    }


    // 更新暂停状态信息
    updatePauseStatusDisplay();
    
    // 更新主操作区域的按钮状态
    updateMainOperationButtons();
    
    // 更新暂停/继续按钮状态
    updatePauseResumeButtons();
    
    // 更新最后更新时间显示
    updateLastUpdateTime();
}

function updateLastUpdateTime() {
    if (AppState.lastUpdateTime) {
        const timeDiff = new Date() - AppState.lastUpdateTime;
        const seconds = Math.floor(timeDiff / 1000);
        
        // 可以在页面某处显示最后更新时间
        // 例如：在状态栏添加一个小的时间戳显示
    }
}

function updatePauseStatusDisplay() {
    // 检查是否有暂停状态显示区域
    let pauseStatusDiv = document.getElementById('pause-status-display');
    
    if (AppState.deviceStatus === 'paused' && (AppState.currentStepInfo || AppState.nextActionInfo)) {
        // 如果不存在暂停状态显示区域，创建一个
        if (!pauseStatusDiv) {
            pauseStatusDiv = document.createElement('div');
            pauseStatusDiv.id = 'pause-status-display';
            pauseStatusDiv.className = 'pause-status-info';
            pauseStatusDiv.innerHTML = `
                <div class="pause-status-header">
                    <i class="fas fa-pause-circle"></i>
                    <h3>反应已暂停</h3>
                </div>
                <div class="pause-status-content">
                    <div class="status-item">
                        <label>当前位置:</label>
                        <span id="current-step-display">-</span>
                    </div>
                    <div class="status-item">
                        <label>下一动作:</label>
                        <span id="next-action-display">-</span>
                    </div>
                </div>
            `;
            
            // 将暂停状态显示插入到状态栏之后
            const statusBar = document.querySelector('.status-bar');
            if (statusBar) {
                statusBar.insertAdjacentElement('afterend', pauseStatusDiv);
            }
        }
        
        // 更新暂停状态信息
        const currentStepDisplay = document.getElementById('current-step-display');
        const nextActionDisplay = document.getElementById('next-action-display');
        
        if (currentStepDisplay) {
            currentStepDisplay.textContent = AppState.currentStepInfo || `步骤 ${AppState.currentStepIndex}`;
        }
        if (nextActionDisplay) {
            nextActionDisplay.textContent = AppState.nextActionInfo || '等待继续';
        }
        
        pauseStatusDiv.style.display = 'block';
    } else {
        // 隐藏暂停状态显示
        if (pauseStatusDiv) {
            pauseStatusDiv.style.display = 'none';
        }
    }
}

function updateMainOperationButtons() {
    // 根据当前状态启用/禁用主要操作按钮
    const fillBtn = document.getElementById('fill_btn');
    const reactionBtn = document.getElementById('reaction_btn');
    
    // 填充管路需要试剂配置
    if (fillBtn) {
        const fillCheck = document.getElementById('fill_check');
        if (fillCheck) {
            const canFill = AppState.currentReagentConfig && AppState.deviceStatus === 'idle';
            fillCheck.disabled = !canFill;
            if (!canFill) {
                fillCheck.checked = false;
                fillBtn.disabled = true;
            }
        }
    }
    
    // 反应需要试剂配置和流程配置，且设备空闲
    if (reactionBtn) {
        const reactionCheck = document.getElementById('reaction_check');
        if (reactionCheck) {
            const canReact = AppState.currentReagentConfig && 
                           AppState.currentInjectConfig && 
                           (AppState.deviceStatus === 'idle' || AppState.deviceStatus === 'paused');
            reactionCheck.disabled = !canReact;
            if (!canReact) {
                reactionCheck.checked = false;
                reactionBtn.disabled = true;
            }
        }
    }
}

function updatePauseResumeButtons() {
    const pauseBtn = document.getElementById('pause-btn');
    const resumeBtn = document.getElementById('resume-btn');
    
    if (pauseBtn && resumeBtn) {
        if (AppState.deviceStatus === 'reacting') {
            pauseBtn.style.display = 'inline-flex';
            resumeBtn.style.display = 'none';
        } else if (AppState.deviceStatus === 'paused') {
            pauseBtn.style.display = 'none';
            resumeBtn.style.display = 'inline-flex';
        } else {
            pauseBtn.style.display = 'inline-flex';
            resumeBtn.style.display = 'none';
        }
    }
}

function getStatusText(status) {
    const statusMap = {
        'idle': '空闲',
        'working': '工作中',
        'error': '错误',
        'initializing': '初始化中',
        'washing': '清洗中',
        'filling': '填充中',
        'reacting': '反应中',
        'paused': '已暂停'
    };
    return statusMap[status] || status;
}

function getStatusClass(status) {
    const classMap = {
        'idle': 'success',
        'working': 'warning',
        'error': 'danger',
        'initializing': 'warning',
        'washing': 'warning',
        'filling': 'warning',
        'reacting': 'warning',
        'paused': 'warning'
    };
    return classMap[status] || '';
}

// 在页面卸载时关闭连接
window.addEventListener('beforeunload', () => {
    if (statusEventSource) {
        statusEventSource.close();
    }
    if (reconnectTimer) {
        clearTimeout(reconnectTimer);
    }
    if (pollingTimer) {
        clearInterval(pollingTimer);
    }
});

// ========== 配置管理 ==========
async function loadAllConfigs() {
    try {
        // 加载试剂配置列表
        const reagentResponse = await fetch('/api/configs/reagents');
        const reagentData = await reagentResponse.json();
        if (reagentData.success) {
            updateReagentConfigSelect(reagentData.configs);
        }
        
        // 加载反应流程列表
        const injectResponse = await fetch('/api/configs/injects');
        const injectData = await injectResponse.json();
        if (injectData.success) {
            updateInjectConfigSelect(injectData.configs);
        }
        
    } catch (error) {
        console.error("加载配置列表失败:", error);
    }
}

function updateReagentConfigSelect(configs) {
    const select = document.getElementById('config_select');
    if (!select) return;
    
    const currentValue = select.value;
    select.innerHTML = '<option value="">--选择配置--</option>';
    
    configs.forEach(config => {
        const option = document.createElement('option');
        option.value = config.name;
        option.textContent = config.display_name;
        
        // 标记当前应用的配置
        if (config.name === AppState.currentReagentConfig) {
            option.textContent += ' (当前应用)';
            option.style.fontWeight = 'bold';
            option.style.color = '#28a745';
        }
        
        // 恢复之前的选择
        if (config.name === currentValue) {
            option.selected = true;
        }
        
        select.appendChild(option);
    });
}

function updateInjectConfigSelect(configs) {
    const select = document.getElementById('inject-config-select');
    if (!select) return;
    
    const currentValue = select.value;
    select.innerHTML = '<option value="">--选择流程--</option>';
    
    // 根据当前试剂配置过滤流程
    const filteredConfigs = configs.filter(config => {
        return !config.reagent_config || config.reagent_config === AppState.currentReagentConfig;
    });
    
    filteredConfigs.forEach(config => {
        const option = document.createElement('option');
        option.value = config.name;
        option.textContent = config.display_name;
        
        // 显示关联的试剂配置
        if (config.reagent_config && config.reagent_config !== AppState.currentReagentConfig) {
            option.textContent += ` (需要: ${config.reagent_config})`;
            option.disabled = true;
            option.style.color = '#6c757d';
        } else if (config.reagent_config) {
            option.textContent += ` (${config.reagent_config})`;
        }
        
        // 标记当前应用的流程
        if (config.name === AppState.currentInjectConfig) {
            option.textContent += ' (当前应用)';
            option.style.fontWeight = 'bold';
            option.style.color = '#28a745';
        }
        
        // 恢复之前的选择
        if (config.name === currentValue) {
            option.selected = true;
        }
        
        select.appendChild(option);
    });
}

// ========== 工具函数 ==========
function validateConfigName(name) {
    if (!name || name.trim().length === 0) {
        return { valid: false, message: '配置名称不能为空' };
    }
    
    if (name.length > 50) {
        return { valid: false, message: '配置名称不能超过50个字符' };
    }
    
    if (name.length < 2) {
        return { valid: false, message: '配置名称至少需要2个字符' };
    }
    
    // 检查特殊字符
    const invalidChars = /[<>:"/\\|?*\x00-\x1f]/;
    if (invalidChars.test(name)) {
        return { valid: false, message: '配置名称包含无效字符' };
    }
    
    return { valid: true };
}

function showValidationError(inputElement, message) {
    inputElement.style.borderColor = '#dc3545';
    inputElement.style.backgroundColor = 'rgba(220, 53, 69, 0.1)';
    showNotification(message, 'error');
    inputElement.focus();
}

function clearValidationError(inputElement) {
    inputElement.style.borderColor = '';
    inputElement.style.backgroundColor = '';
}

function getConfigDisplayName(filename) {
    return filename.replace('_reagents.json', '').replace('_inject.json', '');
}

// ========== 设备操作 ==========
async function sendOperation(action) {
    // 显示加载状态
    const button = event.target;
    const originalText = button.innerHTML;
    button.disabled = true;
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
    
    try {
        const response = await fetch('/api/device/operation', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ action: action })
        });
        
        const data = await response.json();
        if (data.success) {
            showNotification(data.message);
            // 更新设备状态
            if (data.device_status) {
                AppState.deviceStatus = data.device_status;
                debouncedStatusUpdate();
            }
        } else {
            showNotification(data.message || '操作失败', 'error');
        }
    } catch (error) {
        console.error('操作失败:', error);
        showNotification('操作失败', 'error');
    } finally {
        // 恢复按钮状态
        button.disabled = false;
        button.innerHTML = originalText;
    }
}

// ========== 试剂配置管理 ==========
async function loadReagentConfig(configName) {
    try {
        const response = await fetch(`/api/configs/reagents/${encodeURIComponent(configName)}`);
        const data = await response.json();
        
        if (data.success) {
            loadReagentConfigToForm(data.config);
            // 加载配置后，更新配置名称输入框
            const configNameInput = document.getElementById('config_name_input');
            if (configNameInput) {
                configNameInput.value = getConfigDisplayName(configName);
            }
            showNotification(`已加载配置: ${getConfigDisplayName(configName)}`);
        } else {
            showNotification(data.message || '加载配置失败', 'error');
        }
    } catch (error) {
        console.error('加载配置失败:', error);
        showNotification('加载配置失败', 'error');
    }
}

function loadReagentConfigToForm(config) {
    // 清空现有配置
    clearReagentForm();
    
    // 加载配置到表单
    for (let i = 1; i <= 9; i++) {
        const input = document.querySelector(`input[name="reagent${i}"]`);
        if (input) {
            const portConfig = config.find(item => item.port === i);
            input.value = portConfig ? portConfig.reagent : '';
        }
    }
    
    // 更新可用试剂列表
    updateAvailableReagents();
}

function updateAvailableReagents() {
    const availableReagents = [];
    for (let i = 3; i <= 9; i++) {
        const input = document.querySelector(`input[name="reagent${i}"]`);
        if (input && input.value.trim()) {
            availableReagents.push(input.value.trim());
        }
    }
    
    AppState.availableReagents = availableReagents;
    
    // 更新所有步骤中的试剂选择下拉框
    document.querySelectorAll('.step-row select[name*="_reagent"]').forEach(select => {
        const currentValue = select.value;
        select.innerHTML = '<option value="">请选择试剂</option>';
        
        availableReagents.forEach(reagent => {
            const option = document.createElement('option');
            option.value = reagent;
            option.textContent = reagent;
            if (reagent === currentValue) {
                option.selected = true;
            }
            select.appendChild(option);
        });
    });
}

function collectReagentConfig() {
    const config = [];
    for (let i = 1; i <= 9; i++) {
        const input = document.querySelector(`input[name="reagent${i}"]`);
        if (input) {
            config.push({
                port: i,
                reagent: input.value.trim()
            });
        }
    }
    return config;
}

function clearReagentForm() {
    for (let i = 3; i <= 9; i++) {
        const input = document.querySelector(`input[name="reagent${i}"]`);
        if (input) {
            input.value = '';
            clearValidationError(input);
        }
    }
    updateAvailableReagents();
}

async function saveReagentConfig() {
    const configNameInput = document.getElementById('config_name_input');
    if (!configNameInput) {
        showNotification('配置名称输入框未找到', 'error');
        return;
    }
    
    const configName = configNameInput.value.trim();
    
    // 验证配置名称
    const nameValidation = validateConfigName(configName);
    if (!nameValidation.valid) {
        showValidationError(configNameInput, nameValidation.message);
        return;
    }
    
    const config = collectReagentConfig();
    
    // 验证配置内容 - 至少要有一个试剂
    const reagentPorts = config.filter(item => item.port >= 3 && item.reagent.trim());
    if (reagentPorts.length === 0) {
        showNotification('请至少配置一个试剂（端口3-9）', 'error');
        const firstEmptyInput = document.querySelector('input[name="reagent3"]');
        if (firstEmptyInput) {
            firstEmptyInput.focus();
            showValidationError(firstEmptyInput, '请配置试剂');
        }
        return;
    }
    
    // 检查试剂名称重复
    const reagentNames = reagentPorts.map(item => item.reagent.trim());
    const uniqueNames = [...new Set(reagentNames)];
    if (reagentNames.length !== uniqueNames.length) {
        showNotification('试剂名称不能重复', 'error');
        return;
    }
    
    // 清除验证错误样式
    clearValidationError(configNameInput);
    
    // 显示保存进度
    const saveBtn = document.getElementById('save_new_config_btn');
    if (saveBtn) {
        const originalText = saveBtn.innerHTML;
        saveBtn.innerHTML = '<i class="loading"></i> 保存中...';
        saveBtn.disabled = true;
        
        try {
            const response = await fetch('/api/configs/reagents', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    name: configName,
                    config: config
                })
            });
            
            const data = await response.json();
            
            if (data.success) {
                const reagentCount = reagentPorts.length;
                showNotification(`配置已保存: ${configName} (${reagentCount}个试剂)`);
                
                // 刷新配置列表
                await loadAllConfigs();
                
                // 清空输入框，准备下次输入
                configNameInput.value = '';
                
                // 在下拉框中选中刚保存的配置
                const selectElement = document.getElementById('config_select');
                if (selectElement) {
                    selectElement.value = configName + '_reagents.json';
                }
                
            } else {
                showNotification(data.message || '保存失败', 'error');
            }
            
        } catch (error) {
            console.error('保存配置失败:', error);
            showNotification('保存配置失败: ' + error.message, 'error');
        } finally {
            // 恢复按钮状态
            saveBtn.innerHTML = originalText;
            saveBtn.disabled = false;
        }
    }
}

async function deleteReagentConfig() {
    const configSelect = document.getElementById('config_select');
    if (!configSelect) return;
    
    const configName = configSelect.value;
    
    if (!configName || configName === 'reagents.json') {
        showNotification('请选择要删除的配置（不能删除系统主配置）', 'error');
        return;
    }
    
    const displayName = getConfigDisplayName(configName);
    if (!confirm(`确定要删除配置 "${displayName}" 吗？`)) return;
    
    try {
        const response = await fetch(`/api/configs/reagents/${encodeURIComponent(configName)}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        if (data.success) {
            showNotification(`配置已删除: ${displayName}`);
            // 清空表单和选择
            clearReagentForm();
            configSelect.value = '';
            const configNameInput = document.getElementById('config_name_input');
            if (configNameInput) {
                configNameInput.value = '';
            }
            // 刷新配置列表
            await loadAllConfigs();
            
            // 如果删除的是当前应用的配置，更新状态
            if (configName === AppState.currentReagentConfig) {
                AppState.currentReagentConfig = null;
                debouncedStatusUpdate();
            }
        } else {
            showNotification(data.message || '删除失败', 'error');
        }
    } catch (error) {
        console.error('删除配置失败:', error);
        showNotification('删除配置失败', 'error');
    }
}

async function applyReagentConfig() {
    const configSelect = document.getElementById('config_select');
    if (!configSelect) return;
    
    const selectedConfig = configSelect.value;
    
    if (!selectedConfig) {
        showNotification('请先选择要应用的配置', 'error');
        return;
    }
    
    const configName = getConfigDisplayName(selectedConfig);
    
    try {
        // 先获取选中的配置数据
        const response = await fetch(`/api/configs/reagents/${encodeURIComponent(selectedConfig)}`);
        const data = await response.json();
        
        if (!data.success) {
            showNotification('无法加载选中的配置', 'error');
            return;
        }
        
        // 应用配置到系统
        const applyResponse = await fetch('/api/system/reagent-config', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                config_name: configName,
                config: data.config
            })
        });
        
        const applyData = await applyResponse.json();
        if (applyData.success) {
            AppState.currentReagentConfig = configName;
            // AppState.isReagentLocked = false;
            debouncedStatusUpdate();
            showNotification(`试剂配置 "${configName}" 已应用到系统`);
            
            // 关闭模态框
            const reagentModal = document.getElementById('reagent-modal');
            if (reagentModal) {
                reagentModal.style.display = 'none';
                document.body.style.overflow = 'auto';
            }
        } else {
            showNotification(applyData.message || '应用配置失败', 'error');
        }
    } catch (error) {
        console.error('应用配置失败:', error);
        showNotification('应用配置失败', 'error');
    }
}

// ========== 反应流程配置管理 ==========
async function loadInjectConfig(configName) {
    try {
        const response = await fetch(`/api/configs/injects/${encodeURIComponent(configName)}`);
        const data = await response.json();
        
        if (data.success) {
            loadInjectConfigToForm(data.config);
            // 加载配置后，更新流程名称输入框
            const injectNameInput = document.getElementById('new-inject-config-name');
            if (injectNameInput) {
                injectNameInput.value = getConfigDisplayName(configName);
            }
            showNotification(`已加载流程: ${getConfigDisplayName(configName)}`);
        } else {
            showNotification(data.message || '加载流程失败', 'error');
        }
    } catch (error) {
        console.error('加载流程失败:', error);
        showNotification('加载流程失败', 'error');
    }
}

function loadInjectConfigToForm(config) {
    // 清空现有步骤
    clearAllSteps(false);
    
    // 加载步骤
    const steps = config.steps || config; // 兼容新旧格式
    
    if (Array.isArray(steps) && steps.length > 0) {
        steps.forEach(step => {
            addStep();
            const lastStep = document.querySelector('.step-row:last-child');
            
            if (lastStep) {
                const selectElement = lastStep.querySelector('select[name*="_reagent"]');
                const timesInput = lastStep.querySelector('input[name*="_times"]');
                const timewaitInput = lastStep.querySelector('input[name*="_timewait"]');
                const temperatureInput = lastStep.querySelector('input[name*="_temperature"]');
                
                if (selectElement) selectElement.value = step.reagent || '';
                if (timesInput) timesInput.value = step.times || step.cycles || 1;
                if (timewaitInput) timewaitInput.value = step.timewait || 10;
                if (temperatureInput) temperatureInput.value = step.temperature || 25;
            }
        });
        
        updatePreview();
    }
}



async function saveInjectConfig() {
    const configNameInput = document.getElementById('new-inject-config-name');
    if (!configNameInput) {
        showNotification('流程名称输入框未找到', 'error');
        return;
    }
    
    const configName = configNameInput.value.trim();
    
    // 验证流程名称
    const nameValidation = validateConfigName(configName);
    if (!nameValidation.valid) {
        showValidationError(configNameInput, nameValidation.message);
        return;
    }
    
    // 检查是否有试剂配置
    if (!AppState.currentReagentConfig) {
        showNotification('请先选择并应用试剂配置', 'error');
        return;
    }
    
    const stepsData = collectStepsData();
    
    // 验证步骤数量
    if (stepsData.length === 0) {
        showNotification('请至少添加一个步骤', 'error');
        const addStepBtn = document.getElementById('add-step-btn');
        if (addStepBtn) addStepBtn.focus();
        return;
    }
    
    // 验证所有步骤的完整性
    const incompleteSteps = stepsData.filter(step => !step.reagent);
    if (incompleteSteps.length > 0) {
        showNotification(`第${incompleteSteps[0].index}步未选择试剂`, 'error');
        return;
    }
    
    // 清除验证错误样式
    clearValidationError(configNameInput);
    
    // 显示保存进度
    const saveBtn = document.getElementById('save-inject-config-btn');
    if (saveBtn) {
        const originalText = saveBtn.innerHTML;
        saveBtn.innerHTML = '<i class="loading"></i> 保存中...';
        saveBtn.disabled = true;
        
        try {
            const response = await fetch('/api/configs/injects', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    name: configName,
                    reagent_config: AppState.currentReagentConfig,
                    steps: stepsData
                })
            });
            
            const data = await response.json();
            
            if (data.success) {
                showNotification(`流程已保存: ${configName} (${stepsData.length}个步骤)`);
                
                // 刷新配置列表
                await loadAllConfigs();
                
                // 清空输入框，准备下次输入
                configNameInput.value = '';
                
                // 在下拉框中选中刚保存的配置
                const selectElement = document.getElementById('inject-config-select');
                if (selectElement) {
                    selectElement.value = configName + '_inject.json';
                }
                
            } else {
                showNotification(data.message || '保存失败', 'error');
            }
            
        } catch (error) {
            console.error('保存流程失败:', error);
            showNotification('保存流程失败: ' + error.message, 'error');
        } finally {
            // 恢复按钮状态
            saveBtn.innerHTML = originalText;
            saveBtn.disabled = false;
        }
    }
}

async function deleteInjectConfig() {
    const configSelect = document.getElementById('inject-config-select');
    if (!configSelect) return;
    
    const configName = configSelect.value;
    
    if (!configName || configName === 'inject_steps.json') {
        showNotification('请选择要删除的流程（不能删除系统主流程）', 'error');
        return;
    }
    
    const displayName = getConfigDisplayName(configName);
    if (!confirm(`确定要删除流程 "${displayName}" 吗？`)) return;
    
    try {
        const response = await fetch(`/api/configs/injects/${encodeURIComponent(configName)}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        if (data.success) {
            showNotification(`流程已删除: ${displayName}`);
            // 清空表单和选择
            clearAllSteps(false);
            configSelect.value = '';
            const injectNameInput = document.getElementById('new-inject-config-name');
            if (injectNameInput) {
                injectNameInput.value = '';
            }
            // 刷新配置列表
            await loadAllConfigs();
            
            // 如果删除的是当前应用的流程，更新状态
            if (configName === AppState.currentInjectConfig) {
                AppState.currentInjectConfig = null;
                debouncedStatusUpdate();
            }
        } else {
            showNotification(data.message || '删除失败', 'error');
        }
    } catch (error) {
        console.error('删除流程失败:', error);
        showNotification('删除流程失败', 'error');
    }
}

async function applyInjectConfig() {
    const configSelect = document.getElementById('inject-config-select');
    if (!configSelect) return;
    
    const selectedConfig = configSelect.value;
    
    if (!selectedConfig) {
        showNotification('请先选择要应用的流程', 'error');
        return;
    }
    
    if (!AppState.currentReagentConfig) {
        showNotification('请先应用试剂配置', 'error');
        return;
    }
    
    const configName = getConfigDisplayName(selectedConfig);
    
    try {
        // 先获取选中的配置数据
        const response = await fetch(`/api/configs/injects/${encodeURIComponent(selectedConfig)}`);
        const data = await response.json();
        
        if (!data.success) {
            showNotification('无法加载选中的流程', 'error');
            return;
        }
        
        const steps = data.config.steps || data.config; // 兼容新旧格式
        
        // 应用流程到系统
        const applyResponse = await fetch('/api/system/inject-config', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                config_name: configName,
                reagent_config: AppState.currentReagentConfig,
                steps: steps
            })
        });
        
        const applyData = await applyResponse.json();
        if (applyData.success) {
            AppState.currentInjectConfig = configName;
            debouncedStatusUpdate();
            showNotification(`反应流程 "${configName}" 已应用到系统`);
            
            // 关闭模态框
            const injectModal = document.getElementById('inject-modal');
            if (injectModal) {
                injectModal.style.display = 'none';
                document.body.style.overflow = 'auto';
            }
        } else {
            showNotification(applyData.message || '应用流程失败', 'error');
        }
    } catch (error) {
        console.error('应用流程失败:', error);
        showNotification('应用流程失败', 'error');
    }
}

// ========== 步骤管理 ==========
function addStep() {
    updateAvailableReagents(); 
    // 检查是否有试剂配置
    if (AppState.availableReagents.length === 0) {
        showNotification('请先在试剂配置中设置试剂（端口3-9）', 'error');
        return;
    }
    
    AppState.stepCounter++;
    const stepsContainer = document.getElementById('steps-container');
    if (!stepsContainer) return;
    
    // 移除空状态提示
    const emptySteps = stepsContainer.querySelector('.empty-steps-row');
    if (emptySteps) {
        emptySteps.remove();
    }

    const stepHtml = `
    <div class="step-row" data-step="${AppState.stepCounter}">
        <div class="step-number">${AppState.stepCounter}</div>
        <select name="step_${AppState.stepCounter}_reagent" onchange="updatePreview()" required>
            <option value="">请选择试剂</option>
            ${AppState.availableReagents.map(reagent => 
                `<option value="${reagent}">${reagent}</option>`
            ).join('')}
        </select>
        <input type="number" name="step_${AppState.stepCounter}_times" min="1" max="99" value="1" onchange="updatePreview()" required>
        <input type="number" name="step_${AppState.stepCounter}_timewait" min="0" max="3600" value="10" onchange="updatePreview()" required>
        <input type="number" name="step_${AppState.stepCounter}_temperature" min="0" max="100" value="25" onchange="updatePreview()" required>
        <div class="step-actions">
            <button type="button" class="step-action-btn up" onclick="moveStepUp(${AppState.stepCounter})" title="上移">
                <i class="fas fa-arrow-up"></i>
            </button>
            <button type="button" class="step-action-btn down" onclick="moveStepDown(${AppState.stepCounter})" title="下移">
                <i class="fas fa-arrow-down"></i>
            </button>
            <button type="button" class="step-action-btn delete" onclick="removeStep(${AppState.stepCounter})" title="删除">
                <i class="fas fa-trash"></i>
            </button>
        </div>
    </div>
    `;

    stepsContainer.insertAdjacentHTML('beforeend', stepHtml);
    updateStepNumbers();
    updatePreview();
    
    // 滚动到新添加的步骤并聚焦到试剂选择
    setTimeout(() => {
        const newStep = stepsContainer.querySelector(`[data-step="${AppState.stepCounter}"]`);
        if (newStep) {
            newStep.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            const selectElement = newStep.querySelector('select');
            if (selectElement) selectElement.focus();
        }
    }, 100);
}

function removeStep(stepId) {
    if (!confirm('确定要删除这个步骤吗？')) return;
    
    const stepElement = document.querySelector(`[data-step="${stepId}"]`);
    if (stepElement) {
        stepElement.remove();
        updateStepNumbers();
        updatePreview();
        
        // 如果没有步骤了，显示空状态
        const stepsContainer = document.getElementById('steps-container');
        if (stepsContainer && stepsContainer.children.length === 0) {
            stepsContainer.innerHTML = `
            <div class="empty-steps-row">
                <div style="text-align: center; padding: 30px; color: #999;">
                    <i class="fas fa-plus-circle" style="font-size: 2rem; margin-bottom: 10px;"></i>
                    <p>暂无步骤，点击"添加步骤"开始配置</p>
                </div>
            </div>
            `;
        }
    }
}

function moveStepUp(stepId) {
    const stepElement = document.querySelector(`[data-step="${stepId}"]`);
    const prevStep = stepElement?.previousElementSibling;
    
    if (prevStep && !prevStep.classList.contains('empty-steps-row')) {
        stepElement.parentNode.insertBefore(stepElement, prevStep);
        updateStepNumbers();
        updatePreview();
        
        // 确保移动后的步骤可见
        stepElement.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }
}

function moveStepDown(stepId) {
    const stepElement = document.querySelector(`[data-step="${stepId}"]`);
    const nextStep = stepElement?.nextElementSibling;
    
    if (nextStep) {
        stepElement.parentNode.insertBefore(nextStep, stepElement);
        updateStepNumbers();
        updatePreview();
        
        // 确保移动后的步骤可见
        stepElement.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }
}

function clearAllSteps(needConfirm = true) {
    if (needConfirm && !confirm('确定要清空所有步骤吗？')) return;
    
    const stepsContainer = document.getElementById('steps-container');
    if (stepsContainer) {
        stepsContainer.innerHTML = `
        <div class="empty-steps-row">
            <div style="text-align: center; padding: 30px; color: #999;">
                <i class="fas fa-plus-circle" style="font-size: 2rem; margin-bottom: 10px;"></i>
                <p>暂无步骤，点击"添加步骤"开始配置</p>
            </div>
        </div>
        `;
    }
    AppState.stepCounter = 0;
    updatePreview();
}

function updateStepNumbers() {
   const steps = document.querySelectorAll('.step-row:not(.empty-steps-row)');
   steps.forEach((step, index) => {
       const stepNumber = step.querySelector('.step-number');
       if (stepNumber) {
           stepNumber.textContent = index + 1;
       }
       
       const upBtn = step.querySelector('.step-action-btn.up');
       const downBtn = step.querySelector('.step-action-btn.down');
       
       if (upBtn) upBtn.disabled = index === 0;
       if (downBtn) downBtn.disabled = index === steps.length - 1;
   });
   
   const stepCountElement = document.querySelector('.step-count');
   if (stepCountElement) {
       stepCountElement.textContent = `(${steps.length} 步)`;
   }
}

function collectStepsData() {
    const steps = [];
    const stepRows = document.querySelectorAll('.step-row:not(.empty-steps-row)');
    
    stepRows.forEach((row, index) => {
        const reagentSelect = row.querySelector('select[name*="_reagent"]');
        const timesInput = row.querySelector('input[name*="_times"]');
        const timewaitInput = row.querySelector('input[name*="_timewait"]');
        const temperatureInput = row.querySelector('input[name*="_temperature"]');
        
        if (reagentSelect && timesInput && timewaitInput && temperatureInput) {
            steps.push({
                index: index + 1,
                reagent: reagentSelect.value,
                times: parseInt(timesInput.value) || 1,
                timewait: parseInt(timewaitInput.value) || 10,
                temperature: parseFloat(temperatureInput.value) || 25
            });
        }
    });
    
    return steps;
}



function updatePreview() {
    const steps = collectStepsData();
    const validSteps = steps.filter(step => step.reagent);
    
    // 更新步骤计数
    const stepCountElement = document.querySelector('.step-count');
    if (stepCountElement) {
        stepCountElement.textContent = `(${validSteps.length} 步)`;
    }
    
    // 计算总时间
    let totalTime = 0;
    let minTemp = Infinity;
    let maxTemp = -Infinity;
    
    validSteps.forEach(step => {
        // 每个步骤的时间 = (等待时间 + 操作时间估算) * 循环次数
        const stepTime = (step.timewait + 30) * step.times; // 假设每次操作需要30秒
        totalTime += stepTime;
        
        // 更新温度范围
        minTemp = Math.min(minTemp, step.temperature);
        maxTemp = Math.max(maxTemp, step.temperature);
    });
    
    // 更新统计信息
    const totalStepsElement = document.getElementById('total-steps');
    const totalTimeElement = document.getElementById('total-time');
    const tempRangeElement = document.getElementById('temp-range');
    
    if (totalStepsElement) {
        totalStepsElement.textContent = validSteps.length;
    }
    
    if (totalTimeElement) {
        const minutes = Math.floor(totalTime / 60);
        const seconds = totalTime % 60;
        if (minutes > 0) {
            totalTimeElement.textContent = `${minutes}分${seconds}秒`;
        } else {
            totalTimeElement.textContent = `${seconds}秒`;
        }
    }
    
    if (tempRangeElement) {
        if (validSteps.length > 0) {
            if (minTemp === maxTemp) {
                tempRangeElement.textContent = `${minTemp}°C`;
            } else {
                tempRangeElement.textContent = `${minTemp}°C - ${maxTemp}°C`;
            }
        } else {
            tempRangeElement.textContent = '-';
        }
    }
}


window.addStep = addStep;
window.removeStep = removeStep;
window.moveStepUp = moveStepUp;
window.moveStepDown = moveStepDown;
window.updatePreview = updatePreview;
window.clearAllSteps = clearAllSteps;